<!-- AuditManagement.vue -->
<template>


  <div class="audit-container">

    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px" style="margin-bottom: 20px">
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
            v-model="queryParams.auditStatus"
            placeholder="审核状态"
            clearable      style="width: 200px"
        >
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="0" />
          <el-option label="已批准" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table :data="auditMessages" style="width: 100%">

      <el-table-column prop="title" align="center" label="请求标题" width="180"></el-table-column>
      <<el-table-column label="关联订单编号" align="center" width="180">
      <template #default="scope">
        <router-link :to="'/orderDetails/orderDetails?id=' + scope.row.orderId" class="blue-underline">
          <span>{{ scope.row.orderId }}</span>
        </router-link>
      </template>
    </el-table-column>
      <el-table-column prop="time" align="center" label="消息日期" width="180">
        <template #default="scope">
          {{ (scope.row.time) }}
        </template>
      </el-table-column>
        <el-table-column prop="content" align="center" label="变更请求内容" width="400">
        <template #default="scope">
          <div v-if="typeof scope.row.content === 'string' && scope.row.title ==='订单变更通知'">
            <template v-if="isJSON(scope.row.content)">
              <div v-for="(change, key) in JSON.parse(scope.row.content)" :key="key">
                {{ getChangeDescription(key, change) }}
              </div>
            </template>
          </div>
          <div v-else-if="scope.row.title ==='新增商品通知'">{{ JSON.parse(scope.row.content).changes}}</div>
          <div v-else-if="scope.row.title ==='商品修改通知'">{{ JSON.parse(scope.row.content).changes}}</div>
          <div v-else-if="scope.row.title ==='批量变更通知'">
            <template v-if="isJSON(scope.row.content)">
              <div v-for="(change, index) in JSON.parse(scope.row.content).changes" :key="index">
                {{ change.description }}
              </div>
            </template>
            <span v-else>数据格式异常</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="审核状态" width="180">
        <template #default="scope">
          <el-tag  v-if="scope.row.auditStatus === 0" >待审核</el-tag>
          <el-tag v-else-if="scope.row.auditStatus === 1">已批准</el-tag>
          <el-tag v-else-if="scope.row.auditStatus === 2">已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Check" @click="approveAudit(scope.row)" v-show="scope.row.auditStatus===0">批准</el-button>
          <el-button link type="danger" icon="Close" @click="rejectAudit(scope.row)" v-show="scope.row.auditStatus===0" >拒绝</el-button>
          <el-button link type="primary" icon="View" @click="viewAudit(scope.row)" v-show="scope.row.auditStatus===1" >查看详情</el-button>
          <el-button link type="primary" icon="View" @click="viewAudit(scope.row)" v-show="scope.row.auditStatus===2" >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { listMessage , updateMessage,getMessage } from "@/api/system/message.js";
import {getOrder, updateOrder} from "@/api/system/order.js";
import {getCustomerAddr, updateAddr} from "@/api/system/addr.js";
import {updateDetail , getDetail,addDetail} from "@/api/system/detail.js";
import useUserStore from "@/store/modules/user.js";
import * as areaData from "element-china-area-data";

const useStore = useUserStore();
const router = useRouter();

export default {
  name: "AuditManagement",
  data() {
    return {

      queryParams: {
        auditStatus: undefined
      },

      audit_status: [
        { value: 0, label: '待审核' },
        { value: 1, label: '已批准' },
        { value: 2, label: '已拒绝' }
      ],

      pageNum: 1,
      pageSize: 5,
      total: 0,
      filterStatus: null,
      auditMessages: [],
      order: {},
      fieldLabels: {
        orderId: '订单编号',
        orderStatus: '订单状态',
        orderDate: '订单日期',
        businessType: '业务类型',
        customerId: '客户名称',
        paymentMethod: '付款方式',
        transportMode: '配送方式',
        logisticsNumber: '物流单号',
        consignee: '收货人',
        phone: '手机号码',
        zipcode: '邮政编码',
        streetAddress: '详细地址',
        state: '省份',
        city: '城市',
        district: '区县',
        productId: '商品编号',
        merchandiseName: '商品名称',
        merchandiseCategory: '商品类别',
        manufacturer: '生产厂商',
        productPrice: '商品价格',
        productSalesQuantity: '商品数量',
        subtotal: '小计',
        totalAmount: '总金额',
        warehouseCode: '仓库编号',
        remark: '备注'
      },
      selectedOptions: ['13', '1301', '130104'],
      router,

    };
  },
  mounted() {
    this.loadAuditMessages();
  },
  methods: {

    handleQuery() {
      this.pageNum = 1;
      console.log(this.queryParams)
      this.loadAuditMessages();
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        auditStatus: undefined
      };
      this.handleQuery();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.loadAuditMessages();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.loadAuditMessages();
    },

    // 修改加载消息方法
    async loadAuditMessages() {
      try {
        const params = {
          userId: useStore.id,
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          auditStatus: this.queryParams.auditStatus
        };

        const res = await listMessage(params);
        this.auditMessages = res.rows.sort((a, b) => {
          return new Date(b.time) - new Date(a.time)
        });
        this.total = res.total;
        console.log('this.auditMessages',this.auditMessages)
      } catch (error) {
        console.error('获取审核消息失败:', error);
      }
    },

    // 添加日期格式化方法


    namesToCodes(names) {
      let codes = [];
      let currentData = areaData.regionData;
      names.forEach(name => {
        let found = false;
        for (let key in currentData) {
          if (currentData[key].label === name) {
            codes.push(currentData[key].value);
            if (currentData[key].children) {
              currentData = currentData[key].children;
              found = true;
              break;
            } else {
              found = true;
              break;
            }
          }
        }
        if (!found) {
          console.warn(`Could not find the area with name: ${name}`);
          return [];
        }
      });
      return codes;
    },

    /**
     * 将区域编码转换为文本
     */
    codeToText(code) {
      const find = (data, code) => {
        for (let key in data) {
          if (data[key].value === code) {
            return data[key].label;
          }
          if (data[key].children) {
            const result = find(data[key].children, code);
            if (result) return result;
          }
        }
        return null;
      };
      return find(areaData.regionData, code);
    },

    isJSON(str) {
      try {
        JSON.parse(str);
      } catch (e) {
        return false;
      }
      return true;
    },
    getChangeDescription(key, change) {
      const label = this.fieldLabels[key] || key;
      return `${label}: 由 ${change.oldValue} 变更为 ${change.newValue}`;
    },
    getCustomerAddr() {
      getCustomerAddr(this.order.customerId,this.order.addressId).then(response => {
        this.customerAddr = response.data;
        this.selectedOptions= this.namesToCodes([this.customerAddr.state, this.customerAddr.city, this.customerAddr.district])
      }).catch(error => {
        console.error(error);
        throw error;
      });
    },
    getOrderLink(orderId) {
      // 根据实际情况调整链接格式
      return `/orderEdit/orderEdit?id=${orderId}`;
    },
    // loadAuditMessages() {
    //   getMessage(useStore.id).then(response => {
    //     this.auditMessages = response.rows;
    //   }).catch(error => {
    //     console.error('获取审核消息通知失败:', error);
    //   });
    // },
    updateAudit(messageId , status){
      const auditData = {
        userId: useStore.id,
        messageId: messageId,
        auditStatus: status // 设置审核状态为已批准
      };
      updateMessage(auditData).then(response => {
        this.$message.success('修改请求已批准');
        this.loadAuditMessages(); // 刷新审核消息通知
      }).catch(error => {
        this.$message.error('批准修改请求失败');
        console.error('批准修改请求失败:', error);
      });
    },


    // 在approveAudit方法中完善处理逻辑
    async approveAudit(auditMessage) {
      this.$confirm('是否批准该修改请求?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 解析变更内容
          const content = JSON.parse(auditMessage.changes);
          const orderId = auditMessage.orderId;

          // 获取最新订单信息
          const orderRes = await getOrder(orderId);
          const order = orderRes.data;

          // 按顺序处理每个变更
          for (const change of content) {
            switch (change.type) {
              case 'add':
                await this.handleAddOperation(order, change);
                break;

              case 'modify':
                await this.handleModifyOperation(order,change);
                break;

              case 'add-products':
                await this.handleProductAdd(change.data);
                break;

              case 'update-base':
                await this.handleOrderUpdate(orderId, change.data);
                break;

              default:
                console.warn('未知变更类型:', change.type);
            }
          }

          // 更新订单状态
          await updateOrder({
            orderId: orderId,
            orderStatus: '4' // 设置为待发货状态
          });

          // 更新消息状态
          await this.updateAudit(auditMessage.messageId, 1);

          this.$message.success('变更已成功应用，订单状态已更新为待发货');
          this.loadAuditMessages();

        } catch (error) {
          this.$message.error(`操作失败: ${error.message}`);
          console.error('审核批准失败:', error);
        }
      });
    },

// 处理地址变更
    async handleAddOperation(order, changeData) {
      // 获取当前地址

      //[{"type":"add","addressId":"1","products":[{"id":"005","name":"冷冻牛肉","subtotal":"300.00","quantity":1}]}]
      // 构建更新数据
      changeData.products.forEach(product => {
        const updateData = {
          orderId: order.orderId,
          productId: product.id,
          productSalesQuantity: product.quantity,
          discount:parseFloat(0).toFixed(2),
          warehouseCode: 'WH-HEB-001',
          subtotal: product.subtotal,
          totalAmount: product.subtotal*product.quantity,
          addressId: changeData.addressId,
        };
        addDetail(updateData)
})

    },

// 处理商品更新
    async handleModifyOperation(order,changeData) {

      //[{"type":"modify","productId":"004","oldQuantity":1,"newQuantity":2}]
      //[{"type":"modify","productId":"004","addressId":"1","oldQuantity":1,"newQuantity":4}]
      //[{"type":"modify","productId":"C0003","addressId":"1","oldQuantity":1,"newQuantity":2}]
      // 验证必要字段
      if (!order.orderId || !changeData.productId) {
        throw new Error('缺失必要字段：orderId或productId');
      }

      // 构建更新数据
      const updateParams = {
        orderId: order.orderId,
        productId: changeData.productId,
        productSalesQuantity: changeData.newQuantity,
        addressId: changeData.addressId,
      };

      console.log('更新数据', updateParams)

      await updateDetail(updateParams);
    },

// 处理商品新增
    async handleProductAdd(changeData) {
      // 检查是否重复商品
      const existingRes = await getDetail(changeData.orderId);
      const existingProducts = existingRes.data.map(d => d.productId);

      for (const item of changeData) {
        if (existingProducts.includes(item.productId)) {
          throw new Error(`商品${item.productId}已存在，无法重复添加`);
        }
        await addDetail(item);
      }
    },

// 处理订单基础信息更新
    async handleOrderUpdate(orderId, changeData) {
      const validFields = [
        'orderStatus',
        'paymentMethod',
        'businessType',
        'customerId'
      ];

      // 过滤非法字段
      const updateData = Object.keys(changeData)
          .filter(key => validFields.includes(key))
          .reduce((obj, key) => {
            obj[key] = changeData[key];
            return obj;
          }, {orderId});

      await updateOrder(updateData);
    },

    async handleReceiverUpdate(details, order) {
      // 获取当前地址信息
      const addrRes = await getCustomerAddr(order.customerId, order.addressId);
      const currentAddr = addrRes.data;

      // 构建更新数据（只更新变更字段）
      const updateData = {
        addressId: order.addressId,
        customerId: order.customerId,
        consignee: details.consignee || currentAddr.consignee,
        phone: details.phone || currentAddr.phone,
        zipcode: details.zipcode || currentAddr.zipcode,
        streetAddress: details.streetAddress || currentAddr.streetAddress,
        state: details.state || currentAddr.state,
        city: details.city || currentAddr.city,
        district: details.district || currentAddr.district
      };

      await updateAddr(updateData);
    },

    rejectAudit(auditMessage) {
      this.$confirm('是否拒绝该修改请求?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
       this.updateAudit(auditMessage.messageId,2)
      });
    }
  }
}
</script>

<style scoped>
.audit-container {
  width: 90%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
}
.blue-underline {
  color: cornflowerblue;
  text-decoration: underline;
}
.el-form--inline .el-form-item {
  margin-right: 20px;
}
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
